<template>
  <div>
    <!--Modal 添加编辑成员 start-->
    <Modal
      :title="formValidate.id?'编辑用户':'添加用户'"
      @on-visible-change="onChangeVisibleModal"
      v-model="isShowAddOrUpdateUserModal"
      width="740"
    >
      <div>
        <!--Form 添加编辑成员表单 start-->
        <Form :label-width="100" :model="formValidate" :rules="ruleValidate" ref="formValidate">
          <Row>
            <Col span="12">
              <FormItem label="工号" prop="workNo">
                <Input
                  :disabled="formValidate.id?true:false"
                  :maxlength="30"
                  @on-keydown="formValidate.workNo=formValidate.workNo.replace(/^ +| +$/g,'')"
                  @on-keyup="formValidate.workNo=formValidate.workNo.replace(/^ +| +$/g,'')"
                  class="form-width"
                  placeholder="请输入工号"
                  v-model="formValidate.workNo"
                />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="用户名" prop="username">
                <Input
                  :disabled="formValidate.id?true:false"
                  :maxlength="30"
                  @on-keydown="formValidate.username=formValidate.username.replace(/^ +| +$/g,'')"
                  @on-keyup="formValidate.username=formValidate.username.replace(/^ +| +$/g,'')"
                  class="form-width"
                  placeholder="请输入用户名"
                  v-model="formValidate.username"
                />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
              <FormItem label="姓名" prop="actualName">
                <Input
                  :maxlength="30"
                  @on-keydown="formValidate.actualName=formValidate.actualName.replace(/^ +| +$/g,'')"
                  @on-keyup="formValidate.actualName=formValidate.actualName.replace(/^ +| +$/g,'')"
                  class="form-width"
                  placeholder="请输入姓名"
                  v-model="formValidate.actualName"
                />
              </FormItem>
            </Col>
             <Col span="12">
              <FormItem label="别名" prop="nickName">
                <Input
                 :maxlength="30"
                   @on-keydown="formValidate.nickName=formValidate.nickName.replace(/^ +| +$/g,'')"
                  @on-keyup="formValidate.nickName=formValidate.nickName.replace(/^ +| +$/g,'')"
                  class="form-width"
                  placeholder="请输入别名"
                  v-model="formValidate.nickName"
                />
              </FormItem>
            </Col>
            </Row>
            <Row>
             <Col span="12">
              <FormItem label="密码" prop="password" v-if="!formValidate.id">
                <Input
                  @on-keydown="formValidate.loginPwd=formValidate.password.replace(/^ +| +$/g,'')"
                  @on-keyup="formValidate.loginPwd=formValidate.password.replace(/^ +| +$/g,'')"
                  class="form-width"
                  placeholder="请输入密码"
                  type="password"
                  v-model="formValidate.password"
                />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="确认密码" prop="passwordAgain" v-if="!formValidate.id">
                <Input
                  @on-keydown="formValidate.passwordAgain=formValidate.passwordAgain.replace(/^ +| +$/g,'')"
                  @on-keyup="formValidate.passwordAgain=formValidate.passwordAgain.replace(/^ +| +$/g,'')"
                  class="form-width"
                  placeholder="请输入确认密码"
                  type="password"
                  v-model="formValidate.passwordAgain"
                />
              </FormItem>
            </Col>
            </Row>
            <Row>
             <Col span="12">
              <FormItem class="select-class" label="所属机构" prop="orgId">
                <Select class="form-width" v-model="formValidate.orgId" @on-select='selectOrg'>
                  <Option
                    :key="item.id"
                    :value="item.id"
                    v-for="item in orgList"
                  >{{ item.orgName }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem class="select-class" label="所属部门" prop="departmentId">
                <Treeselect
                  placeholder="请选择部门"
                  v-model="formValidate.departmentId"
                  :options="departmentList"
                  noChildrenText="无子部门"
                  zIndex="99999"
                  @select="selectNode">
                  <div slot="option-label" slot-scope="{ node }" style="white-space: nowrap; font-size: 14px">
                        {{ node.raw.id}} ({{ node.raw.departmentName}})
                      </div>
                      <div slot="value-label" slot-scope="{ node }">{{ node.raw.id}} ({{ node.raw.departmentName}})</div>
                </Treeselect>
              </FormItem>
            </Col>
            </Row>
            <Row>
            <Col span="12">
              <FormItem label="手机" prop="phone">
                <Input
                  @on-keyup="formValidate.phone=formValidate.phone.replace(/^ +| +$/g,'')"
                  class="form-width"
                  placeholder="请输入手机号"
                  v-model="formValidate.phone"
                ></Input>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="电子邮箱" prop="email">
                <Input
                  class="form-width"
                  placeholder="请输入邮箱地址"
                  type="email"
                  v-model="formValidate.email"
                ></Input>
              </FormItem>
            </Col>
            </Row>
            <Row>
            <Col span="12">
              <FormItem class="select-class" label="用户类型" prop="userType">
                <Select class="form-width" v-model="formValidate.userType">
                  <Option
                    :key="item.value"
                    :value="item.value"
                    v-for="item in userTypeList"
                  >{{ item.label }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem class="select-class" label="职务" prop="positionId">
                <Select class="form-width" v-model="formValidate.positionId">
                  <Option
                    :key="item.value"
                    :value="item.value"
                    v-for="item in positionListData"
                  >{{ item.label }}</Option>
                </Select>
              </FormItem>
            </Col>
            </Row>
            <Row>
            <Col span="12">
              <FormItem class="select-class" label="角色分配" prop="roleId">
                <Select class="form-width"  v-model="formValidate.roleId">
                  <Option
                    :key="item.id"
                    :value="item.id"
                    v-for="item in roleList"
                  >{{ item.roleName }}</Option>
                </Select>
              </FormItem>
            </Col>
            </Row>
            <Row>
            <Col span="24">
              <FormItem label="描述" prop="remark">
                <Input
                  class="form-width"
                  placeholder="请输入描述"
                  type="textarea"
                   @input="descInput"
                  :maxlength="maxlength"
                  :autosize="{ minRows: 5, maxRows: 8 }"
                  v-model="formValidate.remark"
                />
                <span class="text">{{ remnant }}/{{maxlength}}</span>
              </FormItem>
            </Col>
          </Row>
        </Form>
        <!--Form 添加编辑成员表单 end-->
      </div>
      <div slot="footer">
        <Button @click="cancel" type="text">取消</Button>
        <Button :loading="isShowLoading" @click="submitFormData" class="newBtn" type="primary">提交</Button>
      </div>
    </Modal>
    <!--Modal 添加编辑成员 end-->
  </div>
</template>
<script>
import $ from 'jquery';
import { departmentApi } from '@/api/department';
import { validateTextLength } from '@/lib/util';
import { orgApi } from '@/api/org';
import { userApi } from '@/api/sys-user';
import { roleApi } from '@/api/role';
import { positionApi } from '@/api/position';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import { LOAD_ROOT_OPTIONS } from '@riophae/vue-treeselect';
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect';

export default {
  name: 'UserTableAdd',
  components: {
    Treeselect
  },
  data() {
    return {
      isShowAddOrUpdateUserModal: false,
      isShowLoading: false,
      remnant: 200,
      maxlength:200,
      roleList: [],
      orgList:[],
      userTypeList:[
        { value:0,
          label:'超级管理员'
        },
        { value:1,
          label:'局部管理员'
        },
        { value:2,
          label:'普通用户'
        }
      ],
      departmentList:[],
      positionListData: [],
      isShowTree: false,
      formValidateBackup: {},
      formValidate: {
        id:'',
        workNo:'',
        actualName: '',
        username: '',
        nickName: '',
        orgId:'',
        departmentId:'',
        phone: '',
        idCard: '',
        birthday: '',
        password: '',
        passwordAgain: '',
        email: '',
        positionId:'',
        positionIdList: [],
        roleId:'',
        remark:''
      },
      ruleValidate: {
        workNo: [
          { required: true, message: '工号不能为空', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur'}
        ],
        actualName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        email: [
          { required: false, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确邮箱格式', trigger: 'blur' }
        ],
        departmentId: [
          { required: true, message: '所属部门不能为空', trigger: 'change',type:'number'}
        ],
         orgId: [
          { required: true, message: '所属机构不能为空', trigger: 'change',type:'number' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式错误',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        passwordAgain: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {},
  watch: {
    isShowAddOrUpdateUserModal(val) {
      if (val) {
        this.getPositionListPage();
      }
    }
  },
  filters: {},
  created() {},
  mounted() {
    Object.assign(this.formValidateBackup, this.formValidate);
    this.getOrgList();
    this.getAllRole();
    this.getPositionListPage();
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  methods: {
    // 选择部门点击外部关闭
    clickOutside() {
      if (this.isShowTree) {
        this.isShowTree = false;
      }
    },
    descInput() {
      let txtVal = validateTextLength(this.formValidate.remark);
      this.remnant = this.maxlength - txtVal;
    },
    selectOrg(value){
        this.initDepartment(value.value);
    },
     // 分页查询所有岗位
    async getPositionListPage() {
      let result = await positionApi.getPositionListPage({
        pageNum: 1,
        pageSize: 200,
        sort: false
      });
      let datas = result.data;
      let list = [];
      datas.list.map(item => {
        list.push({
          value: item.id,
          label: item.positionName
        });
      });
      this.positionListData = list;
    },
    async getDetail(userId) {
        const res = await userApi.getUserDetail(userId)
        const data = res.data
        this.formValidate = { ...data }
        if(data.positionRelationList&&data.positionRelationList.length>0){
          this.formValidate.positionId = data.positionRelationList[0].positionId
        }
        this.formValidate.id = data.id
        this.initDepartment(data.orgId)
        this.descInput()
      },
    //初始化部门
    async initDepartment(orgId){
      let result = await departmentApi.getDepartmentByOrgId(orgId);
      this.departmentList = result.data;
    },
    // 弹窗显示隐藏监听
    onChangeVisibleModal(value) {
      if (!value) {
        this.$refs['formValidate'].resetFields();
        this.formValidate = Object.assign({}, this.formValidateBackup);
      }
    },
    // 打开Modal
    showModal(userId) {
      //详情页
      if(userId){
        this.getDetail(userId)
      }
      this.isShowAddOrUpdateUserModal = true;
    },
    cancel() {
      this.formValidate = {};
      // 清空form规则检查
      this.$refs['formValidate'].resetFields();
      this.isShowAddOrUpdateUserModal=false;
    },
    // 点击提交
    submitFormData() {
      this.$refs['formValidate'].validate(valid => {
        if (
          !/^[A-Za-z]+[A-Za-z0-9]{5,17}$/.test(this.formValidate.username) &&
          !this.formValidate.id
        ) {
          this.$Message.error('用户名格式必须由字母开头,5到17位的字母和数字');
          return;
        }
        // if (this.formValidate.idCard) {
        //   if (
        //     !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(
        //       this.formValidate.idCard
        //     )
        //   ) {
        //     this.$Message.error('身份证号码格式不正确！');
        //     return;
        //   }
        // }
        const reg = new RegExp(
          "[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]"
        );
        if (reg.test(this.formValidate.actualName)) {
          this.$Message.error('姓名中不能含有特殊字符！');
          return false;
        }
        if (this.formValidate.passwordAgain !== this.formValidate.loginPwd) {
          this.$Message.error('两次输入密码不一致，请重新输入！！');
          return;
        }
        if(this.formValidate.positionId){
            let positionIdList = [];
            positionIdList.push(this.formValidate.positionId);
            this.formValidate.positionIdList = positionIdList;
        }
        if (valid) {
          if (this.formValidate.id) {
            this.updateUser(this.formValidate);
          } else {
            this.addUser(this.formValidate);
          }
        }
      });
    },
    // 修改用户
    async updateUser(data) {
      try {
        this.isShowLoading = true;
        let result = await userApi.updateUser(data);
        this.isShowAddOrUpdateUserModal = false;
        this.$Message.success('修改用户成功');
        this.$emit('addSuccess');
        this.$refs['formValidate'].resetFields();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.isShowLoading = false;
      }
    },
    // 添加新用户接口
    async addUser(param) {
      try {
        this.isShowLoading = true;
        let result = await userApi.addUser(param);
        if (result.code === 1) {
          this.isShowAddOrUpdateUserModal = false;
          this.$Message.success('添加用户成功');
          this.$emit('addSuccess');
          this.$refs['formValidate'].resetFields();
        } else {
            
        }
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.isShowLoading = false;
      }
    },
    // 加载角色列表
    async getAllRole() {
      let result = await roleApi.getAllRole();
      this.roleList = result.data;
    },
    async getOrgList(){
      let result = await orgApi.getOrgList();
      this.orgList = result.data;
    },
    // 身份证输入失焦校验
    changeIdCard(value) {
      let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (reg.test(value)) {
        let data = value.slice(6, 14);
        let y = data.slice(0, 4);
        let m = data.slice(4, 6);
        let d = data.slice(6, 8);
        this.formValidate.birthday = y + '-' + m + '-' + d;
      }
    },
    selectNode(node, instanceId) {
      // this.selectedNode = node;
    }
  }
};
</script>
<style lang="less" scoped>
.form-width {
  width: 100%;
}
.department-wrap {
  position: absolute;
  background-color: #ffffff;
  padding: 5px;
  border: 1px solid #dedede;
  width: 300px;
  z-index: 9;
  height: 250px;
  overflow-y: scroll;
}
.select-class {
  position: relative;
}
.text{
    position: absolute;
    right: 10px;
    bottom: -5px;
}
</style>
